package com.visitor.web.controller;

import com.visitor.bean.Admin;
import com.visitor.bean.SmartUser;
import com.visitor.service.AdminService;
import com.visitor.service.SmartUserService;
import com.visitor.service.VisitorService;
import com.visitor.web.vm.Response;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@Api(tags="登录管理")
@Controller
@RequestMapping()
public class LoginController {
	@Autowired
	private AdminService adminService;
	@Autowired
	private SmartUserService userService;

	@Autowired
	private VisitorService visitorService;

	@GetMapping("/userIndex")
	public ModelAndView userIndex(HttpSession session,ModelAndView modelAndView){
		SmartUser user=(SmartUser) session.getAttribute("loginUser");
		if(user!=null){
			modelAndView.setViewName("userIndex");
		}else{
			modelAndView.setViewName("login");
		}
		return modelAndView;
	}

	@GetMapping({"index","/"})
	public ModelAndView index(HttpSession session,ModelAndView modelAndView){
		Admin user=(Admin) session.getAttribute("loginAdmin");
		if(user!=null){
			modelAndView.setViewName("index");
			int num=visitorService.getNewVisitor();
			modelAndView.addObject("num",num);
		}else{
			modelAndView.setViewName("login");
		}
		return modelAndView;
	}

	/**
	 * @Description(功能描述): 登录
	 **/
	@GetMapping({"login","logout"})
	public ModelAndView login(HttpSession session,ModelAndView modelAndView){
		modelAndView.setViewName("login");
		return modelAndView;
	}

	@ResponseBody
	@PostMapping("/uploadImg")
	public Response<String> uploadImg(){
		return Response.ok();
	}

	@ResponseBody
	@PostMapping("/doLogin")
	public Response<String> doLogin(HttpSession session, Admin admin){
		if("admin".equalsIgnoreCase(admin.getRole())){
			Admin result= adminService.login(admin);
			if(null!=result){
				session.setAttribute("loginAdmin",result);
				return Response.ok("index");
			}else {
				return  Response.error(300);
			}
		}else{
			SmartUser user=new SmartUser();
			user.setAccount(admin.getAccount());
			user.setPassword(admin.getPasswd());
			user=userService.login(user);
			if(null!=user){
				session.setAttribute("loginUser",user);
				return Response.ok("userIndex");
			}else {
				return  Response.error(300);
			}
		}
	}
}
